/*
 * @Author: your name
 * @Date: 2022-02-05 09:49:05
 * @LastEditTime: 2022-02-10 09:10:08
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \hbs\libs\wechat\web.js
 */
var WxBase = require("./base");
const Req = require('../tools/Tools').Req;
const Ip=`http://172.16.198.11:10348`;//正式地址是10356
class WxWeb extends WxBase {
   constructor(appid, secret, mode = null) {
      super(appid, secret, mode);
   }
   async getWebAccessToken(code) {
      let url1 = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${this.appid}&secret=${this.secret}&code=${code}&grant_type=authorization_code`;
      let ans1 = await Req.get(url1);
      ans1 = JSON.parse(ans1);
      console.log(ans1);
      let url2 = `https://api.weixin.qq.com/sns/userinfo?access_token=${ans1.access_token}&openid=${ans1.openid}&lang=zh_CN`;
      let ans2 = await Req.get(url2);
      ans2 = JSON.parse(ans2);
      return ans2;
   }
   async refreshJsTicket() {
      let at = await this.getAccessToken();
      let url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${at}&type=jsapi`;
      let answer = await Req.get(url).catch((e) => {
         console.log(e);
      });
      answer = JSON.parse(answer);
      if (answer.ticket) {
         return answer.ticket;
      };
      return answer;
   }
   async getJsTicket() {
      let token=await this.#readJsTicket();
      if(!token){
         token=await this.refreshJsTicket();
         await this.#writeJsTicket(token);
      };
      return token;
   }
   async  #readJsTicket() {
      if (this.mode === WxBase.Mode.Redis) {

      } else {
         let ans = this.readJson(this.appid + "_JSTIKET");
         console.log(ans);
         if (ans) {
            let time = ans.date;
            let now = new Date().getTime();
            return ((now - time) / 1000) < 6000 ? ans.token : false;
         };
         return ans;
      }
   }
   async #writeJsTicket(token) {
      if (this.mode === WxBase.Mode.Redis) {
         return true;
      } else {
         this.writeJson({ token, date: new Date().getTime(), appid: this.appid }, this.appid + "_JSTIKET");
         return true;
      };
   }
}
module.exports = WxWeb;